<template>
  <div class="users">
    <div class="users-top">
      <el-input
        placeholder="请输入内容"
        v-model.lazy.trim="queryInput"
        class="input-with-select"
      >
        <el-button
          @click="queryClick()"
          slot="append"
          icon="el-icon-search"
        ></el-button>
      </el-input>
      <el-button @click="dialogVisible = true" class="addUser" type="primary"
        >添加用户</el-button
      >
    </div>
    <div class="users-main">
      <!-- 表格 -->
      <el-table :stripe="true" :data="queryList" border style="width: 100%">
        <el-table-column align="center" type="index" label="编号" width="50">
        </el-table-column>
        <el-table-column prop="username" label="姓名"> </el-table-column>
        <el-table-column prop="email" label="邮箱"> </el-table-column>
        <el-table-column prop="mobile" label="电话"> </el-table-column>
        <el-table-column prop="role_name" label="角色"> </el-table-column>
        <el-table-column label="状态">
          <template v-slot="{ row }">
            <el-switch @change="EditUserState(row)" v-model="row.mg_state">
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column prop="create_time" label="操作">
          <template v-slot="{ row }">
            <el-tooltip
              class="item"
              effect="dark"
              content="修改用户"
              placement="top-start"
            >
              <el-button
                @click="editUser(row)"
                size="mini"
                type="primary"
                icon="el-icon-edit"
              ></el-button>
            </el-tooltip>
            <el-button
              @click="deleteUser(row)"
              size="mini"
              icon="el-icon-delete"
              type="danger"
            ></el-button>
            <el-tooltip
              class="item"
              effect="dark"
              content="分配角色"
              placement="top-start"
            >
              <el-button
                @click="disUser(row)"
                size="mini"
                icon="el-icon-setting"
                type="warning"
              ></el-button
            ></el-tooltip>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 弹出框 -->
    <div class="tankuang">
      <!-- 添加用户 -->
      <el-dialog title="添加用户" :visible.sync="dialogVisible" width="45%">
        <el-form
          :model="addUser"
          :rules="rules"
          ref="addUser"
          label-width="80px"
          class="demo-ruleForm"
        >
          <el-form-item label="用户名" prop="username">
            <el-input v-model="addUser.username"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="addUser.password"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="addUser.email"></el-input>
          </el-form-item>
          <el-form-item label="手机" prop="mobile">
            <el-input v-model="addUser.mobile"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addAUser('addUser')"
            >确 定</el-button
          >
        </span>
      </el-dialog>
      <!-- 修改用户 -->
      <el-dialog
        title="修改用户"
        :visible.sync="dialogVisible2"
        width="45%"
        :before-close="handleClose"
      >
        <el-form
          :model="editUserOld"
          :rules="rules"
          ref="edituser"
          label-width="80px"
          class="demo-ruleForm"
        >
          <el-form-item label="用户名" prop="username">
            <el-input
              :disabled="true"
              v-model="editUserOld.username"
            ></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="editUserOld.email"></el-input>
          </el-form-item>
          <el-form-item label="手机" prop="mobile">
            <el-input v-model="editUserOld.mobile"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible2 = false">取 消</el-button>
          <el-button type="primary" @click="editAUser('edituser')"
            >确 定</el-button
          >
        </span>
      </el-dialog>
      <!-- 分配用户 -->
      <el-dialog
        title="分配角色"
        :visible.sync="dialogVisible3"
        width="45%"
        :before-close="handleClose"
      >
        <span>当前用户 : {{ disAUser.username }}</span>
        <br />
        <br />
        <span>当前角色 : {{ disAUser.role_name }}</span>
        <br />
        <br />
        <span>选择商品分类：</span>
        <el-select v-model="newJueshe" placeholder="请选择新角色">
          <el-option
            v-for="item in juesheLists"
            :key="item.id"
            :label="item.roleName"
            :value="item.id"
          >
          </el-option>
        </el-select>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible3 = false">取 消</el-button>
          <el-button type="primary" @click="isdisUser()">确 定</el-button>
        </span>
      </el-dialog>
    </div>

    <!-- 分页器 -->
    <div
      v-if="queryList.length === userLists.users.length"
      class="users-buttom"
    >
      <el-pagination
        @size-change="getUsersSize"
        @current-change="getUsersPage"
        :current-page="currentPage"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="pagesize"
        layout="total, sizes, prev, pager, next"
        :total="userLists.total"
      >
      </el-pagination>
    </div>
  </div>
</template>
<script>
export default {
  data() {
    //自定义验证规则
    var validatePass = (rule, value, callback) => {
      var re = /^1(3[0-9]|5[189]|8[6789])[0-9]{8}$/;
      if (!re.test(value)) {
        callback(new Error("请输入正确的手机号"));
      } else {
        callback();
      }
    };
    return {
      queryInput: "",
      userLists: {
        users: [],
      },
      queryList: [],
      currentPage: 1,
      pagesize: 5,

      //弹框状态
      dialogVisible: false,
      dialogVisible2: false,
      dialogVisible3: false,

      //添加用户初始化
      addUser: {
        username: "",
        password: "",
        email: "",
        mobile: "",
        id: null,
      },
      //修改用户信息存储
      editUserOld: {
        username: "",
        email: "",
        mobile: "",
      },

      //分配角色
      juesheLists: [],
      disAUser: {},
      props: {
        label: "roleName",
        value: "id",
        expandTrigger: "hover",
      },
      newJueshe: null,
      rules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          // { min: 3, max: 5, message: "长度在 3 到 5 个字符", trigger: "blur" },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          { min: 3, message: "长度需要大于3个字符", trigger: "blur" },
        ],
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          {
            type: "email",
            message: "请输入正确的邮箱地址",
            trigger: ["blur", "change"],
          },
        ],
        mobile: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          {
            validator: validatePass,
            trigger: ["blur", "change"],
          },
        ],
      },
    };
  },
  created() {
    // console.log(1);
    this.getUsers(this.currentPage, this.pagesize);
    this.getJueshe();
    // console.log(this.addAUser());
  },
  methods: {
    //初始获取请求
    async getUsers(page, size) {
      const res = await this.$axios.get(
        `users?pagenum=${page}&&pagesize=${size}`
      );
      this.userLists = res.data.data;
      this.queryList = res.data.data.users;
      this.queryInput = "";
      // console.log(this.userLists);
    },

    //每页条数改变时
    getUsersSize(val) {
      this.pagesize = val;
      this.getUsers(this.currentPage, this.pagesize);
    },
    //每页页码改变
    getUsersPage(val) {
      this.currentPage = val;
      this.getUsers(this.currentPage, this.pagesize);
    },
    //修改用户状态
    async EditUserState(val) {
      const res = await this.$axios.put(
        `users/${val.id}/state/${val.mg_state}`
      );
      if (res.data.meta.msg === "设置状态成功") {
        this.$message({
          message: "设置状态成功",
          type: "success",
        });
      }
    },

    //弹框关闭确认
    handleClose(done) {
      this.$confirm("确认关闭？")
        .then((_) => {
          done();
        })
        .catch((_) => {});
    },

    //确认添加用户
    addAUser(formName) {
      this.$refs[formName].validate(async (valid) => {
        // let res = null;
        if (valid) {
          // console.log(1);
          // console.log(this.addUser);
          //成功
          // console.log(...this.addUser);
          // alert("submit!");
          // console.log(res);
          const res = await this.$axios.post("users", this.addUser);
          console.log(res);
          if (res.data.meta.msg === "创建成功") {
            this.addUser = {
              username: "",
              password: "",
              email: "",
              mobile: "",
            };
            this.dialogVisible = false;
            this.$message({
              message: "创建成功",
              type: "success",
            });
            this.getUsers(this.currentPage, this.pagesize);
          } else if (res.data.meta.msg === "用户名已存在") {
            this.$message({
              message: "用户名已存在",
              type: "warning",
            });
          }
        } else {
          console.log("error submit!!");
          return false;
        }

        // console.log(res);
      });
    },

    //删除用户
    deleteUser(row) {
      // console.log(row);
      const index = this.userLists.users.findIndex((ele) => ele.id === row.id);
      // console.log(index);
      this.$confirm("此操作将永久删除该用户, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          await this.$axios.delete(`users/${row.id}`);
          this.userLists.users.splice(index, 1);
          this.userLists.total -= 1;
          this.$message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    //修改用户
    editUser(row) {
      const { editUserOld } = this;
      // console.log(row);
      editUserOld.username = row.username;
      editUserOld.email = row.email;
      editUserOld.mobile = row.mobile;
      editUserOld.id = row.id;
      this.dialogVisible2 = true;
    },
    editAUser(formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          const res = await this.$axios.put(
            `users/${this.editUserOld.id}`,
            this.editUserOld
          );
          console.log(res);
          if (res.data.meta.msg === "更新成功") {
            this.dialogVisible2 = false;
            this.$message({
              message: "修改成功",
              type: "success",
            });
            this.getUsers(this.currentPage, this.pagesize);
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    //搜索功能
    async queryClick() {
      if (this.queryInput !== "") {
        const res = await this.$axios.get(
          `users?pagenum=${1}&&pagesize=${this.userLists.total}`
        );
        this.queryList = res.data.data.users.filter(
          (ele) => ele.username.includes(this.queryInput) === true
        );
      } else {
        this.queryList = this.userLists.users;
      }
    },
    //获取角色列表
    async getJueshe() {
      const res = await this.$axios.get("roles");
      // console.log(res);
      this.juesheLists = res.data.data;
    },
    //分配角色
    disUser(row) {
      this.disAUser = row;
      this.dialogVisible3 = true;
    },
    async isdisUser() {
      if (this.newJueshe) {
        const res = await this.$axios.put(`users/${this.disAUser.id}/role`, {
          rid: this.newJueshe,
        });

        if (res.data.meta.status === 200) {
          this.$message({
            message: `${res.data.meta.msg}`,
            type: "success",
          });
          const userId = this.queryList.findIndex(
            (ele) => ele.id === this.disAUser.id
          );
          const juesheId = this.juesheLists.findIndex(
            (ele) => ele.id === this.newJueshe
          );
          // console.log(userId, juesheId);
          this.queryList[userId].role_name =
            this.juesheLists[juesheId].roleName;
        } else {
          this.$message.error("分配角色出错");
        }
      }
      this.newJueshe = null;
      this.dialogVisible3 = false;
    },
  },
};
</script>
<style   lang='less'>
.users {
  padding: 15px;
  .users-top {
    width: 500px;
    display: flex;
    .addUser {
      margin-left: 15px;
    }
  }
  .users-main {
    padding: 15px 0;
  }
}
</style>
